# @Time   : 2022-03-03 17:00:00
# @Author : Gavin Jiang
# @Owner  : YSRD (Insights Value)

import importlib
import inspect
import os

from framework.interface.abstract_after_request import AbstractAfterRequest
from framework.interface.abstract_before_request import AbstractBeforeRequest
from framework.the_path import ThePath


class InterceptorLoader:
    INTERCEPTOR_PKG_NAME = 'interceptor'

    @staticmethod
    def __get_file_instance_list(file_name, package_name):
        before_list = []
        after_list = []
        if file_name.endswith('.py') and not file_name.startswith('__init__'):
            module = importlib.import_module(f"{package_name}.{file_name[:-3]}")
            cls_list = inspect.getmembers(module, inspect.isclass)
            for cls_name, cls in cls_list:
                if cls != AbstractBeforeRequest and issubclass(cls, AbstractBeforeRequest):
                    before_list.append(cls())
                if cls != AbstractAfterRequest and issubclass(cls, AbstractAfterRequest):
                    after_list.append(cls())

        return before_list, after_list

    @staticmethod
    def load_interceptors():
        src_path = ThePath.src()

        before_list = []
        after_list = []
        for dir_path, dir_names, files in os.walk(src_path):
            dir_path = dir_path.replace('\\','/')
            if InterceptorLoader.INTERCEPTOR_PKG_NAME in dir_names:
                pkg_name = f"{dir_path.replace(src_path, '').replace('/', '.')[1:]}.{InterceptorLoader.INTERCEPTOR_PKG_NAME}"
                for file in os.listdir(os.path.join(dir_path, InterceptorLoader.INTERCEPTOR_PKG_NAME)):
                    in_file_before_list, in_file_after_list = InterceptorLoader.__get_file_instance_list(file, pkg_name)
                    before_list = before_list + in_file_before_list
                    after_list = after_list + in_file_after_list

        return sorted(before_list, key=lambda x: x.priority(), reverse=True), sorted(after_list, key=lambda x: x.priority(), reverse=True)
